package ms.platform.progress.controller;

import com.alibaba.fastjson.JSONArray;
import ms.platform.email.ExchangeMailService;
import ms.platform.email.MailService;
import ms.platform.plan.dto.FactoryDto;
import ms.platform.plan.dto.TargetDto;
import ms.platform.plan.model.ModelPlan;
import ms.platform.plan.service.BusModelService;
import ms.platform.progress.dto.AnnexDto;
import ms.platform.progress.dto.IndexAuditDto;
import ms.platform.progress.dto.ProgressDetailDto;
import ms.platform.progress.dto.ProgressDto;
import ms.platform.progress.model.AuditResult;
import ms.platform.progress.service.FactoryPlanService;
import ms.platform.progress.service.IndexAuditService;
import ms.platform.system.controller.BaseController;
import ms.platform.system.model.Manufacturer;
import ms.platform.system.service.IndexService;
import ms.platform.util.DateUtil;
import ms.platform.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/bus/index/")
public class IndexAuditController extends BaseController{
	@Autowired
	IndexAuditService indexAuditService;
	@Autowired
	BusModelService busModelService;
	@Autowired
	FactoryPlanService factoryService;
	@Autowired
	private IndexService indexService;
	@Autowired
	private MailService mailService;
	@Autowired
	private ExchangeMailService exchangeMailService;
	/**
	 * 首页审核列表
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/index")
	public String meterList(@RequestParam Map<String,Object> map, HttpServletRequest request){
		try {
			//机种
			if (!StringUtil.isNullOrBlock(map.get("modelType"))) {
				if (!(java.nio.charset.Charset.forName("GBK").newEncoder().canEncode((String) map.get("modelType")))) {
					String fac = (String) map.get("modelType");
					map.put("modelType",new String(fac.getBytes("ISO-8859-1"), "utf-8"));
				}
			}
			//厂商
			if (!StringUtil.isNullOrBlock(map.get("orgName"))) {
				if (!(java.nio.charset.Charset.forName("GBK").newEncoder().canEncode((String) map.get("orgName")))) {
					String fac = (String) map.get("orgName");
					map.put("orgName",new String(fac.getBytes("ISO-8859-1"), "utf-8"));
				}
			}
			if (!StringUtil.isNullOrBlock(map.get("modelCode"))) {
				if (!(java.nio.charset.Charset.forName("GBK").newEncoder().canEncode((String) map.get("modelCode")))) {
					String mode = (String) map.get("modelCode");
					map.put("modelCode",new String(mode.getBytes("ISO-8859-1"), "utf-8"));
				}
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String userId = (String) request.getSession().getAttribute("admin");//当前操作的人id
		List<IndexAuditDto> list = indexAuditService.queryPageAuditList(map, request,userId);
		request.setAttribute("list", list);
		List<FactoryDto> factoryList = busModelService.queryAllFactory("F");
		request.setAttribute("factoryList", factoryList);
		List<TargetDto> mTypeList = busModelService.queryAllmodelType();
	    request.setAttribute("mTypeList", mTypeList);
		request.getSession().setAttribute("meterList", map);
		return "index/indexAudit";
	}
	
	/**
	 * 跳转审核页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/toAudit")
	@ResponseBody
    public Object toAudit(Integer id,HttpServletRequest request){
		ProgressDetailDto detailDto = factoryService.getProgressDetailById(id, false, false, false);

		ModelPlan modelPlan = factoryService.getmodelPlan(detailDto.getModelPlanId());//获取结束时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
		String endDate = sdf.format(modelPlan.getPlanEndTime());
		String newDate = sdf.format(new Date());
		//判断当前时间是否大于计划结束时间
		//如果大于，则沿用计划结束最后天来提交进度
		boolean tempTime = false;
		if (DateUtil.middate(newDate, endDate, sdf) >= 0) {
			detailDto = factoryService.getProgressDetailById(id, false, true, true);
			tempTime = true;
		}


		Map<String,String> map = new HashMap<String,String>();
		if(null != detailDto.getModelPlanId()&& StringUtils.isNotEmpty(detailDto.getPlanProgress())){
			map.put("modelPlanId", detailDto.getModelPlanId().toString());
			map.put("currentPro", detailDto.getPlanProgress());
			map.put("processName", detailDto.getCurrentPro());
			if(StringUtils.isNotEmpty(detailDto.getCurrentPro())){
				Integer modelProcessId = indexAuditService.queryProcessIdByPlanIdAndPlanName(map);
				detailDto.setModelProcessId(modelProcessId);
			}
			ProgressDto dto = factoryService.getPlanStartTimeByProcessNameTwo(map);
			long day = DateUtil.getDayByDateSubraction(DateUtil.convertStringToDate(detailDto.getReportDate(), "yyyy-MM-dd"),dto.getPlanStartTime());
			DecimalFormat df = new DecimalFormat("#");
			detailDto.setPlanPro(df.format(100/(double)dto.getPlanTotalTime()*day));
			if (!StringUtils.isNotBlank(dto.getTargetPre())) {
				detailDto.setTargetPre("0");
			}else{
				detailDto.setTargetPre(dto.getTargetPre());
			}
		}
		if(null != detailDto){
			List<AnnexDto> annexList = factoryService.getProgressAnnexList(detailDto.getId());
			request.setAttribute("annex", annexList);
			detailDto.setAnnexDto(annexList);
		}
		if(tempTime){
			detailDto.setPlanPro("100");//计划结束已经过了 进入这里,计划比例100
		}
        return returnSuccess("操作成功",detailDto);
    }
	
	/**
	 * 审核
	 * @param request
	 * @return
	 */
	@RequestMapping("/audit")
	@ResponseBody
    public Object audit(@RequestParam Map<String,Object> param,HttpServletRequest request){
		String userId = (String) request.getSession().getAttribute("admin");//当前操作的人id
		String flag = indexAuditService.queryRoleIdByUserId(userId);
		String jsonData = param.get("auditData")==null?"":param.get("auditData").toString();
		List<AuditResult> audit = JSONArray.parseArray(jsonData, AuditResult.class);
		if(audit.size()>0){
			//判断是否是拒绝,如果拒绝发送邮件提醒
			if ("3".equals(audit.get(0).getStatus())) {
				IndexAuditDto indexAuditDto = indexAuditService.queryAudit(audit.get(0).getRecordId());
				String model = indexAuditDto.getModelCode();//部品番号
				String advis = audit.get(0).getAdvise();//意见
				String sendMan = indexAuditDto.getCreateBy();//发送人
				Manufacturer user = indexService.queryEail(sendMan);//获取邮箱
				if (user != null) {
					if (!StringUtil.isNullOrBlock(user.getLinkMail())) {//邮件不为空的时候进行发送
						ProgressDetailDto detailDto = factoryService.getProgressDetailById(audit.get(0).getRecordId(), false, false, false);
						String planPro = detailDto.getPlanProgress();//计划进度
						String currentPro = detailDto.getCurrentPro();//当前进度
						String content = "亲爱的厂商：<br/> 您好!<br/>审核不通过提醒! 部品番号:"+model+",计划进度:"+planPro+","+
								"当前进度:"+currentPro+","+"审核意见:"+advis;
						this.sendEmail(user.getLinkMail(),content);
						if (!StringUtil.isNullOrBlock(user.getLinkMailTwo())) {
							this.sendEmail(user.getLinkMailTwo(),content);
						}
					}
				}
			}
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("id", audit.get(0).getRecordId());
			map.put("updatedBy", userId);
			map.put("userId", userId);
			map.put("status", audit.get(0).getStatus());
			if("true".equals(flag)){
				indexAuditService.reviewAudit(map, audit.get(0));
			}else{
				indexAuditService.audit(map, audit.get(0));
			}
		}
        return returnSuccess("操作成功","");
    }

	private void sendEmail(String email, String content) {
		try {
//			mailService.sendHtmlMail(email,"进度审核提醒",content);
			exchangeMailService.send("进度审核提醒",new String[]{email},null,content);
		} catch (MessagingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
